package com.ship.dispatch.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.ship.common.core.base.Export;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.bpm.BpmJsonModelDO;
import com.ship.dispatch.mapper.DispatchExportMapper;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.util.CommonUtil;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class ExportServiceImpl extends BaseServiceImpl<DispatchExportMapper,Export> implements ExportService<Export> {

    @Value("${file_server.host}")
    private String fileServerHost;

    @Autowired
    private RemoteFileService remoteFileService;

    @Override
    public String pageExport(List<?> exportList, Field[] fields, List<String> table, String fileName) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            List<Field> fieldList = new LinkedList<>();
            if (CollectionUtil.isEmpty(table)){
                for (Field field : fields) {
                    String name = field.getName();
                    table.add(name);
                }
            }

            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }

            for (int i = 0; i < fieldList.size(); i++) {
                Field field = fieldList.get(i);
                field.setAccessible(true);
                headerRow.createCell(i).setCellValue(CommonUtil.getFieldLabel(field));
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            // 获取当前日期
            LocalDateTime currentDate = LocalDateTime.now();
            // 格式化日期为指定格式（例如：年月日）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH.mm");
            String formattedDate = currentDate.format(formatter);
            String excelName = (fileName+formattedDate+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
//            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);

            if (file.exists()) {
                if (file.delete()) {
                }
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();
            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }
            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String pageMergeExport(List<?> exportList, Field[] fields, List<String> table, String fileName) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            if (CollectionUtil.isEmpty(table)){
                for (Field field : fields) {
                    String name = field.getName();
                    table.add(name);
                }
            }

            List<Field> fieldList = new LinkedList<>();
            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }

            for (int i = 0; i < fieldList.size(); i++) {
                Field field = fieldList.get(i);
                field.setAccessible(true);
                headerRow.createCell(i).setCellValue(CommonUtil.getFieldLabel(field));
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            String excelName = (fileName+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
//            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);
            if (file.exists()) {
                file.delete();
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();

            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }
            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }


    @Override
    public List<String> listStrByModuleAndUser(String module, Long currentUserId) {
        return this.baseMapper.listStrByModuleAndUser(module,currentUserId);
    }

    public MultipartFile createExcelFile(List<?> exportList, Field[] fields, List<String> table, List<String> tableNameList, String fileName) throws IOException, IllegalAccessException {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式化器
        // 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(fileName);

        // 创建标题行
        int rowNum = 0; // 开始时写入列名
        Row headerRow = sheet.createRow(rowNum++);

        List<Field> fieldList = new LinkedList<>();

        if(table != null){
            for (String comName : table) {
                for (Field field : fields) {
                    String fieldName = field.getName();
                    if(StringUtils.equals(comName,fieldName)){
                        fieldList.add(field);
                        break;
                    }
                }
            }
        }else{
            fieldList = Arrays.asList(fields);
        }

        if (CollectionUtil.isNotEmpty(tableNameList)){
            for (int i = 0; i < tableNameList.size(); i++) {
                headerRow.createCell(i).setCellValue(tableNameList.get(i));
            }
        }else {
            for (int i = 0; i < fieldList.size(); i++) {
                Field field = fieldList.get(i);
                field.setAccessible(true);
                headerRow.createCell(i).setCellValue(CommonUtil.getFieldLabel(field));
            }
        }

        // 填充数据
        for (Object objectData : exportList) {
            Row row = sheet.createRow(rowNum++);
            for (int i = 0; i < fieldList.size(); i++) {
                Field field = fieldList.get(i);
                field.setAccessible(true);
                Object value = field.get(objectData);
                // 检查字段是否为Date类型，如果是则格式化为字符串
                if (value instanceof Date) {
                    Cell cell = row.createCell(i);
                    cell.setCellValue(dateFormatter.format((Date) value));
                }  else {
                    row.createCell(i).setCellValue(value != null ? value.toString() : "");
                }
            }
        }

        for (int i = 0; i < fieldList.size(); i++) {
            boolean isEmptyColumn = true;
            for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                Cell cell = sheet.getRow(j).getCell(i);
                if (cell != null && cell.getCellType() != CellType.BLANK) {
                    isEmptyColumn = false;
                    break;
                }
            }
            if (isEmptyColumn) {
                sheet.setColumnHidden(i, true); // 隐藏为空的列
            }
        }
        // 写入到输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        // 转换为MultipartFile
        byte[] bytes = byteArrayOutputStream.toByteArray();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        String date = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMATTER);
        String fileNames = fileName+date;
        MultipartFile multipartFile = new MockMultipartFile(fileNames+".xlsx", fileNames+".xlsx", "application/vnd.ms-excel", byteArrayInputStream);

        byteArrayOutputStream.close();
        return multipartFile;
    }

    @Override
    public String fileExport(List<?> exportList, Field[] fields, List<String> table, List<String> tableNameList, String fileName) throws IOException, IllegalAccessException {
        MultipartFile file = createExcelFile(exportList, fields, table, tableNameList, fileName);
        R<SysFile> result = remoteFileService.upload(file);
        System.out.println("数据导出文件上传结果日志打印："+result);
        if(result.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String url = result.getData().getHttpUrl();

        String CsoldPart = "http://10.75.34.224:9300/statics";
        String ZsoldPart = "http://10.75.33.149:9300/statics";
        String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
        String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

        String newUrl = "";
        if (url.contains("http://10.75.34.224:9300/statics")) {
            newUrl = url.replace(CsoldPart, CsPart);
        }else if (url.contains("http://10.75.33.149:9300/statics")){
            newUrl = url.replace(ZsoldPart, ZsPart);
        }else {
            newUrl = url;
        }
        return newUrl;
    }

    @Override
    public String createExcelFileDate(List<?> exportList, Field[] fields, List<String> table, List<String> tableNameList, String fileName) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            List<Field> fieldList = new LinkedList<>();

            if (CollectionUtil.isEmpty(table)){
                for (Field field : fields) {
                    String name = field.getName();
                    table.add(name);
                }
            }

            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }
            if (CollectionUtil.isNotEmpty(tableNameList)){
                for (int i = 0; i < tableNameList.size(); i++) {
                    headerRow.createCell(i).setCellValue(tableNameList.get(i));
                }
            }else {
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    headerRow.createCell(i).setCellValue(CommonUtil.getFieldLabel(field));
                }
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            // 获取当前日期
            LocalDateTime currentDate = LocalDateTime.now();
            // 格式化日期为指定格式（例如：年月日）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH.mm");
            String formattedDate = currentDate.format(formatter);
            String excelName = (fileName+formattedDate+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
//            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);
            if (file.exists()) {
                file.delete();
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();

            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }
            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String exportUtil(List<?> exportList, Field[] fields, List<String> table, List<String> tableNameList, String fileName)  {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义日期格式化器
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet(fileName);

            int rowNum = 0; // 开始时写入列名
            Row headerRow = sheet.createRow(rowNum++);

            List<Field> fieldList = new LinkedList<>();

            if (CollectionUtil.isEmpty(table)){
                for (Field field : fields) {
                    String name = field.getName();
                    table.add(name);
                }
            }

            if(table != null){
                for (String comName : table) {
                    for (Field field : fields) {
                        String fieldName = field.getName();
                        if(StringUtils.equals(comName,fieldName)){
                            fieldList.add(field);
                            break;
                        }
                    }
                }
            }else{
                fieldList = Arrays.asList(fields);
            }
            if (CollectionUtil.isNotEmpty(tableNameList)){
                for (int i = 0; i < tableNameList.size(); i++) {
                    headerRow.createCell(i).setCellValue(tableNameList.get(i));
                }
            }else {
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    headerRow.createCell(i).setCellValue(CommonUtil.getFieldLabel(field));
                }
            }

            for (Object objectData : exportList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < fieldList.size(); i++) {
                    Field field = fieldList.get(i);
                    field.setAccessible(true);
                    Object value = field.get(objectData);
                    // 检查字段是否为Date类型，如果是则格式化为字符串
                    if (value instanceof Date) {
                        Cell cell = row.createCell(i);
                        cell.setCellValue(dateFormatter.format((Date) value));
                    }  else {
                        row.createCell(i).setCellValue(value != null ? value.toString() : "");
                    }
                }
            }

            for (int i = 0; i < fieldList.size(); i++) {
                boolean isEmptyColumn = true;
                for (int j = 1; j < rowNum; j++) { // 从第二行开始检查，因为第一行是列名
                    Cell cell = sheet.getRow(j).getCell(i);
                    if (cell != null && cell.getCellType() != CellType.BLANK) {
                        isEmptyColumn = false;
                        break;
                    }
                }
                if (isEmptyColumn) {
                    sheet.setColumnHidden(i, true); // 隐藏为空的列
                }
            }
            // 获取当前日期
            LocalDateTime currentDate = LocalDateTime.now();
            // 格式化日期为指定格式（例如：年月日）
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH.mm");
            String formattedDate = currentDate.format(formatter);
            String excelName = (fileName+formattedDate+".xlsx");
            // 将工作簿保存到文件
            try (FileOutputStream outputStream = new FileOutputStream(excelName)) {
                workbook.write(outputStream);
                outputStream.flush();
            } catch (IOException e) {
                // 处理文件写入异常
                e.printStackTrace();
                return "导出 Excel 文件失败";
            }
            //文件地址
            File file = new File(excelName);
//            //声明参数集合
//            HashMap<String, Object> paramMap = new HashMap<>();
//            //文件
//            paramMap.put("file", file);
//            //输出
//            paramMap.put("output","json");
//            //自定义路径
//            paramMap.put("path","image");
//            //场景
//            paramMap.put("scene","image");
//
//            paramMap.put("filename",excelName);
            //上传
            MultipartFile multipartFile = getMultipartFile(file);
            R<SysFile> result = remoteFileService.upload(multipartFile);
//            String result= HttpUtil.post(fileServerHost+"/group1/upload", paramMap);
            if (file.exists()) {
                file.delete();
            }
//             //使用Gson解析JSON
//            Gson gson = new Gson();
//            JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
//             获取"url"字段的值
//            String url = jsonObject.get("url").getAsString();
//            String url = result.getData().getHttpUrl();
            if(result.getCode() != R.SUCCESS){
                throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
            }
            String url = result.getData().getHttpUrl();

            String CsoldPart = "http://10.75.34.224:9300/statics";
            String ZsoldPart = "http://10.75.33.149:9300/statics";
            String CsPart = "https://lngshippingcs.cgp.cnooc/api/file/statics";
            String ZsPart = "https://lngshipping.cgp.cnooc/api/file/statics";

//            String newUrl = "";
//            if (url.contains("https://lngshipping.cgp.cnooc")) {
//                newUrl = url.replace(ZsPart, ZsoldPart);
//            }else if (url.contains("https://lngshippingcs.cgp.cnooc")){
//                newUrl = url.replace(CsPart, CsoldPart);
//            }else {
//                newUrl = url;
//            }
            String newUrl = "";
            if (url.contains("http://10.75.34.224:9300/statics")) {
                newUrl = url.replace(CsoldPart, CsPart);
            }else if (url.contains("http://10.75.33.149:9300/statics")){
                newUrl = url.replace(ZsoldPart, ZsPart);
            }else {
                newUrl = url;
            }

            return newUrl;
        } catch (IOException e) {
            // 处理工作簿创建异常
            e.printStackTrace();
            return "创建 Excel 工作簿失败";
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
